#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2025-03-13 17:31
# @Author : fanzf
# @Version：V 0.1
# @File : __init__.py.py
# @desc :
from datetime import datetime
import os
import logging
import redis as redis
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_executor import Executor
from flask_redis import FlaskRedis
from concurrent.futures import ThreadPoolExecutor

# 配置服务参数
service_name = "python-flask-service"
ip = "127.0.0.1"
port = 5000


def create_app():
    app = Flask(__name__)
    # 初始化日志
    init_logger(app)
    # 初始化配置
    init_config(app)
    # 初始化异步线程池
    app.config['EXECUTOR_MAX_WORKERS'] = 10
    app.executor = Executor(app)
    # 初始化redis
    init_redis(app)
    # 初始化数据库连接
    app.db = SQLAlchemy(app)
    app.bcrypt = Bcrypt(app)

    # 延迟导入蓝图
    from .routes import bp
    app.register_blueprint(bp, url_prefix='/')

    return app


def init_redis(app):
    # 配置 Redis 连接 URL
    # app.config['REDIS_URL'] = "redis://my-redis:6379/0"
    # app.config['REDIS_URL'] = "redis://127.0.0.1:6379/0"
    # 初始化 Flask-Redis 扩展
    app.redis_client = FlaskRedis(app)
    try:
        # 尝试连接 Redis
        app.redis_client.ping()
        print("===========Redis connection successful")
    except redis.exceptions.ConnectionError as e:
        print("===========Redis connection failed: {}".format(e))
        # 可以选择在这里抛出异常或记录日志
        raise


def init_config(app):
    env = os.environ.get('FLASK_ENV', 'development')  # 默认为开发环境
    if env == 'production':
        app.config.from_object('config.ProductionConfig')
        print("init pro config")
    else:
        app.config.from_object('config.DevelopmentConfig')
        print("init dev config")


def init_logger(app):
    login_manager = LoginManager(app)
    login_manager.login_view = 'login'
    app.logger = setup_logging()


# 配置日志
def setup_logging():
    # 获取当前日期和时间
    now = datetime.now()
    # 格式化为 "yyyymmddhhmmss" 格式
    current_date_str = now.strftime("%Y%m%d%H%M%S")
    my_logger = logging.getLogger('my_logger')
    my_logger.setLevel(logging.DEBUG)
    # 创建一个文件处理器，并设置级别为DEBUG
    fh = logging.FileHandler('my_log_' + current_date_str + '.log', encoding='utf-8')
    fh.setLevel(logging.DEBUG)
    # 创建一个流处理器（控制台输出）
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    # 定义日志格式
    formatter = logging.Formatter('%(asctime)s - %(name)s -  %(threadName)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    # 将文件处理器和流处理器添加到日志记录器
    my_logger.addHandler(fh)
    my_logger.addHandler(ch)
    return my_logger